import json
import re
import datetime
import logging
from django.views import View
from django.http import JsonResponse
from myhome.utils.loginrequired import LoginRequired
from homes.models import House
from .models import Order

logger = logging.getLogger('django')


class OrderView(LoginRequired, View):
    def get(self, request):
        """获取订单列表"""
        # 获取并检验参数
        role = request.GET.get('role')
        if role not in ['custom', 'landlord']:
            return JsonResponse({"errno": "4103", "errmsg": "参数错误"})

        # 分别处理房客与房东的订单列表
        if role == 'custom':
            # 房客订单获取
            orders = Order.objects.filter(user=request.user).order_by('-create_time')
        else:
            # 房东订单获取
            houses = House.objects.filter(user=request.user)
            orders = Order.objects.filter(house__in=houses).order_by('-create_time')

        # 构造响应字典
        data = {"data": {"orders": []}, "errmsg": "OK", "errno": "0"}

        # 获取每个订单的详情
        for order in orders:
            data["data"]["orders"].append(order.get_order())

        return JsonResponse(data)

    def post(self, request):
        """创建订单"""
        # 获取参数
        json_dict = json.loads(request.body.decode())
        house_id = json_dict.get('house_id')
        start_date = json_dict.get('start_date')
        end_date = json_dict.get('end_date')

        # 检验参数
        if not all([house_id, start_date, end_date]):
            return JsonResponse({"errno": "4103", "errmsg": "缺少参数"})

        if not re.match(r'^\d{4}-\d{2}-\d{2}', start_date):  # 检验日期格式
            return JsonResponse({"errno": "4103", "errmsg": "参数错误"})

        if not re.match(r'^\d{4}-\d{2}-\d{2}', end_date):
            return JsonResponse({"errno": "4103", "errmsg": "参数错误"})

        if start_date >= end_date:
            return JsonResponse({"errno": "4103", "errmsg": "时间参数错误"})

        try:
            house = House.objects.get(id=house_id)  # 检验房屋是否存在
        except House.DoesNotExist:
            return JsonResponse({"errno": "4002", "errmsg": "无数据"})

        if house.user == request.user:  # 订单用户是否为房屋主人
            return JsonResponse({"errno": "4105", "errmsg": "用户身份错误"})

        start_date = datetime.datetime.strptime(start_date, '%Y-%m-%d')
        end_date = datetime.datetime.strptime(end_date, '%Y-%m-%d')
        days = (end_date - start_date).days

        # 判断当前房屋是否被预定
        orders = Order.objects.filter(house_id=house_id, begin_date__lt=end_date, end_date__gt=start_date)
        if orders:
            return JsonResponse({"errno": "4003", "errmsg": "已被预定"})

        # 保存订单
        try:
            order = Order.objects.create(
                user=request.user,
                house=house,
                begin_date=start_date,
                end_date=end_date,
                days=days,
                house_price=house.price,
                amount=house.price * days,
                status=Order.ORDER_STATUS["WAIT_ACCEPT"]  # 待接单
            )
        except Exception as e:
            logger.error(e)
            return JsonResponse({"errno": "4004", "errmsg": "预定失败"})

        return JsonResponse({
            "data": {"order_id": order.id},
            "errno": "0",
            "errmsg": "下单成功"
        })


class OrderStatusView(LoginRequired, View):
    def put(self, request, order_id):
        """接单或拒单"""
        # 接收参数
        json_dict = json.loads(request.body.decode())
        action = json_dict.get('action')
        reason = json_dict.get('reason')

        # 检验参数
        if action not in ['accept', 'reject']:
            return JsonResponse({"errno": "4004", "errmsg": "参数错误"})

        try:
            order = Order.objects.get(id=order_id)
        except Order.DoesNotExist:
            return JsonResponse({"errno": "4002", "errmsg": "订单不存在"})

        # 分别处理接单与拒单
        if action == "accept":
            # 接单处理
            try:
                order.status = Order.ORDER_STATUS["WAIT_COMMENT"]
                order.save()
            except Exception as e:
                logger.error(e)
                return JsonResponse({"errno": "4004", "errmsg": "接单失败"})
        else:
            # 拒单处理
            if not reason:
                return JsonResponse({"errno": "4103", "errmsg": "请填写拒单原因"})
            try:
                order.status = Order.ORDER_STATUS["REJECTED"]
                order.comment = reason
                order.save()
            except Exception as e:
                logger.error(e)
                return JsonResponse({"errno": "4004", "errmsg": "拒单出错"})

        return JsonResponse({"errno": "0", "errmsg": "操作成功"})


class OrderCommitView(LoginRequired, View):
    def put(self, request, order_id):
        """发表评论"""
        # 获取并检验参数
        comment = json.loads(request.body.decode()).get('comment')
        if not comment:
            return JsonResponse({"errno": "4103", "errmsg": "缺少参数"})

        try:
            order = Order.objects.get(id=order_id)
        except Order.DoesNotExist:
            return JsonResponse({"errno": "4002", "errmsg": "查询不到订单"})

        # 修改保存评论，订单状态与放完总订单数
        try:
            order.comment = comment
            order.status = Order.ORDER_STATUS["COMPLETE"]
            order.save()
            order.house.order_count += 1
            order.house.save()
        except Exception as e:
            logger.error(e)
            return JsonResponse({"errno": "4004", "errmsg": "评论失败"})

        return JsonResponse({"errno": "0", "errmsg": "评论成功"})




